package com.cms.manage.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class RequestMapToUtil {

	/**
	 * 获取 request 中用POST方式"Content-type"是 "text/plain"发送的 json数据
	 * 
	 * @author: sgy
	 * @date: 2018年8月28日
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> getPostByTextPlain(HttpServletRequest request) {
		String userTotalId ="";
		if(request.getSession().getAttribute(Constant.SESSION_USER_ID)!=null){
			 userTotalId = request.getSession().getAttribute(Constant.SESSION_USER_ID).toString();
		}
		String userTotalNickName ="";
		if(request.getSession().getAttribute(Constant.SESSION_NIKE_NAME)!=null){
			 userTotalNickName = request.getSession().getAttribute(Constant.SESSION_NIKE_NAME).toString();
		}     
		// application/json
		// application/x-www-form-urlencoded
		try {
			if (request.getContentType()!=null&&(request.getContentType().contains("application/json")
					|| request.getContentType().contains("text/plain"))) {
				String s = request.getQueryString();
				BufferedReader reader = request.getReader();
				char[] buf = new char[512];
				int len = 0;
				StringBuffer contentBuffer = new StringBuffer();
				while ((len = reader.read(buf)) != -1) {
					contentBuffer.append(buf, 0, len);
				}
				String content = contentBuffer.toString();
				Map<String, String[]> map = null;
				// 根据json数据中对象的key值及其类型取出相应的参数值
				//map = parseQueryString(content);
				map = parseQueryJsonString(content);
				Map<String, String> params = new HashMap<String, String>(map.size());
				int len1;
				for (Map.Entry<String, String[]> entry : map.entrySet()) {
					len1 = entry.getValue().length;
					if (len1 == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len1 > 1) {
						params.put(entry.getKey(), entry.getValue().toString());
					}
				}
				// params = addHeaders(request,params);
				params.put("userTotalId", userTotalId);
				params.put("userTotalNickName", userTotalNickName);
				return params;
			} else if (request.getContentType()!=null&&(request.getContentType().contains("application/x-www-form-urlencoded")
					|| request.getContentType().contains("multipart/form-data"))) {
				Map<String, String[]> map = null;
				if (request.getMethod().equalsIgnoreCase("POST")) {
					map = request.getParameterMap();
				}
				Map<String, String> params = new HashMap<String, String>(map.size());
				int len;
				for (Map.Entry<String, String[]> entry : map.entrySet()) {
					len = entry.getValue().length;
					if (len == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len > 1) {
						params.put(entry.getKey(), entry.getValue().toString());
					}
				}
				// params = addHeaders(request,params);
				params.put("userTotalId", userTotalId);
				params.put("userTotalNickName", userTotalNickName);
				return params;
				// } else if (request.getContentType()==null){
			} else {
				Map<String, String[]> map = null;
				// 为GET请求时就获取其请求参数的那段信息
				String s = request.getQueryString();
				if (StringUtils.isBlank(s)) {
					return new HashMap<String, String>();
				}
				try {
					// 将得到的HTML数据用UTF-8转码
					s = URLDecoder.decode(s, "UTF-8");
				} catch (UnsupportedEncodingException e) {

				}
				map = parseQueryString(s);
				Map<String, String> params = new HashMap<String, String>(map.size());
				int len;
				for (Map.Entry<String, String[]> entry : map.entrySet()) {
					len = entry.getValue().length;
					if (len == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len > 1) {
						params.put(entry.getKey(), entry.getValue().toString());
					}
				}
				params.put("userTotalId", userTotalId);
				params.put("userTotalNickName", userTotalNickName);
				return params;
			}
		} catch (Exception e) {
			return null;
		}

	}
    //转json数据
	private static Map<String, String[]> parseQueryJsonString(String content) {
		System.out.println(content);
		 JSONObject jsonObject = JSON.parseObject(content);
		 Map<String, String[]> res =new HashMap<String, String[]>();
		Map m = jsonObject; 
        m.forEach((k,v)->{
        	res.put(k.toString(), v.toString().split(","));
        });
		return res;
	}

	// 解析请求
	private static Map<String, String[]> parseQueryString(String queryString) {
		Map<String, String[]> map = new HashMap<String, String[]>();

		String[] params = queryString.split("&");

		for (String param : params) {
			String name = param.split("=")[0];
			String[] value = param.split("=")[1].split(",");

			map.put(name, value);
		}
		return map;
	}

	// 解析header数据
	private static Map<String, String> addHeaders(HttpServletRequest request, Map<String, String> params) {
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			params.put(key, value);
		}
		return params;
	}

	public static Map<String, Object> getPostByTextPlainToObj(HttpServletRequest request) {

		// application/json
		// application/x-www-form-urlencoded
		try {
			if (request.getContentType().contains("application/json")
					|| request.getContentType().contains("text/plain")) {
				String s = request.getQueryString();
				BufferedReader reader = request.getReader();
				char[] buf = new char[512];
				int len = 0;
				StringBuffer contentBuffer = new StringBuffer();
				while ((len = reader.read(buf)) != -1) {
					contentBuffer.append(buf, 0, len);
				}
				String content = contentBuffer.toString();
				Map<String, Object[]> map = null;
				// 根据json数据中对象的key值及其类型取出相应的参数值
				map = parseQueryStringToObj(content);
				Map<String, Object> params = new HashMap<String, Object>(map.size());
				int len1;
				for (Map.Entry<String, Object[]> entry : map.entrySet()) {
					len1 = entry.getValue().length;
					if (len1 == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len1 > 1) {
						params.put(entry.getKey(), entry.getValue());
					}
				}
				// params = addHeaders(request,params);
				return params;
			} else if (request.getContentType().contains("application/x-www-form-urlencoded")
					|| request.getContentType().contains("multipart/form-data")) {
				Map<String, String[]> map = null;
				if (request.getMethod().equalsIgnoreCase("POST")) {
					map = request.getParameterMap();
				}
				Map<String, Object> params = new HashMap<String, Object>(map.size());
				int len;
				for (Map.Entry<String, String[]> entry : map.entrySet()) {
					len = entry.getValue().length;
					if (len == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len > 1) {
						params.put(entry.getKey(), entry.getValue());
					}
				}
				// params = addHeaders(request,params);
				return params;
				// } else if (request.getContentType()==null){
			} else {
				Map<String, Object[]> map = null;
				// 为GET请求时就获取其请求参数的那段信息
				String s = request.getQueryString();
				if (StringUtils.isBlank(s)) {
					return new HashMap<String, Object>();
				}
				try {
					// 将得到的HTML数据用UTF-8转码
					s = URLDecoder.decode(s, "UTF-8");
				} catch (UnsupportedEncodingException e) {

				}
				map = parseQueryStringToObj(s);
				Map<String, Object> params = new HashMap<String, Object>(map.size());
				int len;
				for (Map.Entry<String, Object[]> entry : map.entrySet()) {
					len = entry.getValue().length;
					if (len == 1) {
						params.put(entry.getKey(), entry.getValue()[0]);
					} else if (len > 1) {
						params.put(entry.getKey(), entry.getValue());
					}
				}
				return params;
			}
		} catch (Exception e) {
			return null;
		}

	}

	// 解析请求
	private static Map<String, Object[]> parseQueryStringToObj(String queryString) {
		Map<String, Object[]> map = new HashMap<String, Object[]>();

		String[] params = queryString.split("&");

		for (String param : params) {
			String name = param.split("=")[0];
			Object[] value = param.split("=")[1].split(",");

			map.put(name, value);
		}
		return map;
	}

	// 解析header数据
	private static Map<String, Object> addHeadersToObj(HttpServletRequest request, Map<String, Object> params) {
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			Object value = request.getHeader(key);
			params.put(key, value);
		}
		return params;
	}

	// 读取流文件
	public static Map<String, Object> getPostByTextPlain(HttpServletRequest request,String fileKey) throws Exception {

		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断是否是多数据段提交格式
		Map<String, Object> rs = new HashMap<>();
		if(!"".equals(fileKey)){
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> fileList= multiRequest.getFiles(fileKey);	
			rs.put("fileList", fileList);
		}
		}
		Map<String, String>param = RequestMapToUtil.getPostByTextPlain(request);		
		rs.put("param", param);
		return rs;
	}
}
